﻿#pragma once
#include "Common.h"

// 定长内存池
template<class T>
class ObjectPool
{
public:
	ObjectPool()
		:_memory(nullptr),
		_RemainBytes(0),
		_freeList(nullptr)
	{}

	T* New()
	{
		T* obj = nullptr;
		// 把还回来的地址优先使用
		if (_freeList)
		{
			obj = (T*)_freeList;
			void* next = *(void**)_freeList;
			_freeList = next;
		}
		else
		{
			// 如果内存不足
			size_t objSize = sizeof(T) < sizeof(void*) ? sizeof(void*) : sizeof(T);
			if (_RemainBytes < objSize)
			{
				/*if (_RemainBytes)
				{
					free(_memory);
				}*/
				_memory = (char*)malloc(128 * 1024);
				if (_memory == nullptr)
				{
					throw std::bad_alloc();
				}
				_RemainBytes = 128 * 1024;
			}
			
			obj = (T*)_memory;
			_memory += objSize;
			_RemainBytes -= objSize;
		}

		// 定位new，调用 T 的构造函数
		new(obj)T;
		return obj;
	}
	//T* t_New()
	//{
	//	T* obj = nullptr;
	//	// 如果⾃由链表有对象，直接取⼀个
	//	if (_freeList)
	//	{
	//		obj = (T*)_freeList;
	//		_freeList = *((void**)_freeList);
	//	}
	//	else
	//	{
	//		if (_RemainBytes < sizeof(T))
	//		{
	//			_RemainBytes = 128 * 1024;
	//			_memory = (char*)malloc(_RemainBytes);
	//			// _memory = (char*)SystemAlloc(_RemainBytes);
	//			if (_memory == nullptr)
	//			{
	//				throw std::bad_alloc();
	//			}
	//		}
	//		obj = (T*)_memory;
	//		size_t objSize = sizeof(T) < sizeof(void*) ? sizeof(void*) :
	//			sizeof(T);
	//		_memory += objSize;
	//		_RemainBytes -= objSize;
	//	}
	//	// 使⽤定位new调⽤T的构造函数初始化
	//	new(obj)T;
	//	return obj;
	//}


	void Delete(T* delObj)
	{
		// 显式调用 T 的析构
		delObj->~T();

		*(void**)delObj = _freeList;
		_freeList = delObj;
	}

private:
	char* _memory; // 内存池的起始地址
	size_t _RemainBytes; // 剩余字节

	void* _freeList; // 释放列表
};

struct TreeNode
{
	int val;
	TreeNode* left;
	TreeNode* right;
};

void TestObjectPool()
{
	// 申请释放的轮次
	const size_t Rounds = 3;
	// 每轮申请释放多少次
	const size_t N = 100000;
	std::vector<TreeNode*> v1;
	v1.reserve(N);

	size_t begin1 = clock();
	for (size_t j = 0; j < Rounds; ++j)
	{
		for (int i = 0; i < N; ++i)
		{
			v1.push_back(new TreeNode);
		}
		for (int i = 0; i < N; ++i)
		{
			delete v1[i];
		}
		v1.clear();
	}
	size_t end1 = clock();
	

	ObjectPool<TreeNode> TNPool;
	std::vector<TreeNode*> v2;
	v2.reserve(N);

	size_t begin2 = clock();
	for (size_t j = 0; j < Rounds; ++j)
	{
		for (int i = 0; i < N; ++i)
		{
			v2.push_back(TNPool.New());
		}
		for (int i = 0; i < N; ++i)
		{
			TNPool.Delete(v2[i]);
		}
		v2.clear();
	}
	size_t end2 = clock();
	

	cout << "new cost time:" << end1 - begin1 << endl;
	cout << "object pool cost time:" << end2 - begin2 << endl;
}